﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Headers;
using WebApiClientCore;
using WebApiClientCore.Attributes;

namespace ExampleService.APIContract
{
    public class ContractAttribute : Attribute
    {

    }

    public class AuthTokenFilter : IApiFilter
    {
        public Task OnRequestAsync(ApiRequestContext context)
        {
            var httpContextAccessor = context.HttpContext.ServiceProvider.GetRequiredService<IHttpContextAccessor>();
            var httpContext = httpContextAccessor.HttpContext;
            if (httpContext == null)
            {
                return Task.CompletedTask;
            }
            if (!httpContext.Request.Headers.TryGetValue("Authorization", out var accessToken))
            {
                return Task.CompletedTask;
            }
            if (!string.IsNullOrEmpty(accessToken))
            {
                string tokens = accessToken.ToString().Split(" ")[1];
                context.HttpContext.RequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens);
            }
            return Task.CompletedTask;
        }
        public Task OnResponseAsync(ApiResponseContext context)
        {
            return Task.CompletedTask;
        }
    }

}
